package com.cube.share.proxy.jdk;

import com.cube.share.proxy.stat.Person;
import com.cube.share.proxy.stat.Tenant;
import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * @author cube.li
 * @date 2021/3/6 18:27
 * @description jdk动态代理
 */
public class JdkProxyClient {

    public static void main(String[] args) {
        //目标对象
        Person target = new Tenant("李四");
        //InvocationHandler
        InvocationHandler handler = new RentInvocationHandler(target);
        //获取代理对象
        Person proxyInstance = (Person) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
        //通过代理对象调用
        proxyInstance.rentHouse();
        printProxyClass();
    }

    /**
     * 将jdk动态代理的类输出
     */
    private static void printProxyClass() {
        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class<?>[]{Person.class});
        try {
            String pathDir = "E:\\";
            String path = "$Proxy0.class";
            File f = new File(pathDir);
            if (!f.exists()) {
                f.mkdir();
            }
            path = f.getAbsolutePath() + path;
            f = new File(path);
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();

            try (FileOutputStream fos = new FileOutputStream(path)) {
                fos.write(bytes);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
